package 比较;

import java.util.Arrays;
import java.util.Comparator;

class Student implements Comparable<Student>{//这个是泛型,规定比较的类型
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }


    @Override
    public int compareTo(Student o) {
        System.out.println("调用了重写的compareTo方法");
        return this.age - o.age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

class AgeComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.age - o2.age;
    }
}
class NameComparator implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}

    public class Test {
        public static void bubbleSort(Comparable[] comparables) {
            for (int i = 0; i < comparables.length-1; i++) {
                for (int j = 0; j < comparables.length-1-i; j++) {
                    if(comparables[j].compareTo(comparables[j+1]) > 0) {
                        Comparable temp = comparables[j];//此时,重写的compareTo方法其实是比较的age
                        comparables[j] = comparables[j+1];
                        comparables[j+1] = temp;
                    }
                }
            }

        }
    public static void main(String[] args) {

//        Student[] students = new Student[3];
//        students[0] = new Student("zs",15);
//        students[1] = new Student("ls",13);
//        students[2] = new Student("wxw",14);
//        System.out.println("排序前=========");
//        System.out.println(Arrays.toString(students));
//        bubbleSort(students);
//        System.out.println("排序后=========");
//        System.out.println(Arrays.toString(students));
        Comparable comparable = new Student("小白",12);
        //我们能调用toString的原因是,这个方法是Object类的,然后所有的类都继承object类,然后这里student类重写了toString,但是Compareable接口里面是没有toString方法的,那为什么调用的toString还是子类写的方法System.out.println(comparable.toString());//我们能调用toString的原因是,这个方法是Object类的,然后所有的类都继承object类,然后这里student类重写了toString,但是Compareable接口里面是没有toString方法的,那为什么调用的toString还是子类写的方法

    }
}
